package com.yj.springbootsecurity02.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAuthenticationSucessHandler authenticationSucessHandler;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                return User.withUsername("admin").password(passwordEncoder().encode("123")).authorities("admin").build();
            }
        };
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .formLogin()
//                .loginPage("/login.html")
                .loginPage("/require")
                .loginProcessingUrl("/login")
                .successHandler(authenticationSucessHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/login.html", "/require")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf()
                .disable(); //
    }
}
